#START:authorize
#START:layout
class LoginController < ApplicationController
#END:layout

  #START:filter
  before_filter :authorize, :except => :login
#  before_filter :authorize_admin, :on => [:add_user, :delete_user]
  #END:filter
  # . . 
#END:authorize
#START:layout

  #layout "admin"
#END:layout

  #START:index
  def index
    if admin?
      @total_orders = Order.count
    else
      @total_orders = Order.count_by_sql "select count(*) from orders where user = '#{cur_user.name}'"
    end
  end
  #END:index

  # just display the form and wait for user to
  # enter a name and password
  #START:login
  def login
    session[:user_id] = nil
    if request.post?
      user = User.authenticate(params[:name], params[:password])
      if user
        session[:user_id] = user.id
        session[:user_name] = user.name
        redirect_to(:action => "index")
      else
        flash[:error] = "无效的用户/密码"
      end
    end
  end
  #END:login

  #START:add_user
  def add_user
    return if need_admin
    @user = User.new(params[:user])
    if request.post? and @user.save
      flash.now[:notice] = "用户#{@user.name}创建成功"
      @user = User.new
    end
  end
  
  def edit_user
    @user = User.find(params[:id])
    check
  end
  
  def update_user
    @user = User.find(params[:id])
    check
    if @user.update_attributes(params[:user])
      flash[:notice] = '用户信息更新成功.'
      redirect_to :action => 'list_users'
    else
      render :action => 'edit_user'
    end
  end
  
  # . . .
  #END:add_user

  #START:delete_user
  def delete_user
    if need_admin 
      return
    end
    if request.post?
      user = User.find(params[:id])
      begin
        user.destroy
        flash[:notice] = "用户#{user.name}删除成功!"
      rescue Exception => e
        flash[:error] = e.message
      end
    end
    redirect_to(:action => :list_users)
  end
  #END:delete_user

  #START:list_users
  def list_users
    need_admin
    @all_users = User.find(:all)
  end
  #END:list_users
  
  #START:logout
  def logout
    session[:user_id] = nil
    session[:user_name] = nil
    flash[:notice] = "用户注销成功!"
    redirect_to(:action => "login")
  end
  #END:logout
  private
  
  def check    
    if cur_user.id == @user.id
      return true
    else
      return !need_admin
    end
  end
end
